package com.chatplus.application.web.resolver;

import com.chatplus.application.common.crypto.CryptoValue;
import com.chatplus.application.common.crypto.RequestMessageDecryptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@SuppressWarnings("NullableProblems")
public class CryptoValueMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private final RequestMessageDecryptor requestMessageDecryptor;

    public CryptoValueMethodArgumentResolver(RequestMessageDecryptor requestMessageDecryptor) {
        this.requestMessageDecryptor = requestMessageDecryptor;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return CryptoValue.class.isAssignableFrom(parameter.getParameter().getType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String parameterName = parameter.getParameterName();
        if (parameterName != null) {
            String cipherText = webRequest.getParameter(parameterName);
            if (StringUtils.isNotBlank(cipherText)) {
                String rawText = requestMessageDecryptor.decrypt(cipherText);
                return new CryptoValue(cipherText, rawText);
            }
        }
        return null;
    }
}
